using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("news")]
    public class NewsController : ControllerBase
    {
        private readonly INewsService _newsService;
        private readonly ApplicationDbContext _context;

        public NewsController(INewsService newsService, ApplicationDbContext context)
        {
            _newsService = newsService;
            _context = context;
        }

        /// <summary>
        /// 获取新闻列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<R>> GetNewsList()
        {
            var newsList = await _newsService.GetNewsListAsync();
            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = newsList
            });
        }

        /// <summary>
        /// 获取新闻详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<R>> GetNews(long id)
        {
            var news = await _newsService.GetNewsAsync(id);
            if (news == null)
            {
                return Ok(new R { code = 1, msg = "新闻不存在" });
            }

            // 增加点击次数
            await _newsService.IncrementClickCountAsync(id);

            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = news
            });
        }

        /// <summary>
        /// 创建新闻
        /// </summary>
        [HttpPost("save")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<R>> CreateNews([FromBody] News news)
        {
            var result = await _newsService.CreateNewsAsync(news);
            return Ok(new R
            {
                code = 0,
                msg = "保存成功",
                data = result
            });
        }

        /// <summary>
        /// 更新新闻
        /// </summary>
        [HttpPost("update")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<R>> UpdateNews([FromBody] News news)
        {
            var result = await _newsService.UpdateNewsAsync(news);
            if (result == null)
            {
                return Ok(new R { code = 1, msg = "新闻不存在" });
            }

            return Ok(new R
            {
                code = 0,
                msg = "更新成功",
                data = result
            });
        }

        /// <summary>
        /// 删除新闻
        /// </summary>
        [HttpPost("delete/{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<R>> DeleteNews(long id)
        {
            await _newsService.DeleteNewsAsync(id);
            return Ok(new R { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 分页获取新闻
        /// </summary>
        [HttpGet("page")]
        [AllowAnonymous]
        public async Task<IActionResult> GetNewsPage(
            [FromQuery] int page = 1,
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "id",
            [FromQuery] string order = "desc")
        {
            try
            {
                var query = _context.News.AsQueryable();

                // 排序
                if (order.ToLower() == "asc")
                {
                    query = sort.ToLower() switch
                    {
                        "title" => query.OrderBy(n => n.BiaoTi),
                        _ => query.OrderBy(n => n.Id)
                    };
                }
                else
                {
                    query = sort.ToLower() switch
                    {
                        "title" => query.OrderByDescending(n => n.BiaoTi),
                        _ => query.OrderByDescending(n => n.Id)
                    };
                }

                var total = await query.CountAsync();
                var items = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .Select(n => new
                    {
                        id = n.Id,
                        addtime = n.AddTime,
                        title = n.BiaoTi,
                        introduction = n.JianJie,
                        picture = n.TuPian,
                        content = n.NeiRong,
                        clicknum = n.ClickNum
                    })
                    .ToListAsync();

                return Ok(new
                {
                    code = 0,
                    data = new
                    {
                        total,
                        pageSize = limit,
                        totalPage = (int)Math.Ceiling((double)total / limit),
                        currPage = page,
                        list = items
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取新闻分页数据时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }
    }
} 